package com.usefullc.system.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.usefullc.common.constants.SystemConstant;
import com.usefullc.common.enums.DataDictTypeEnum;
import com.usefullc.common.enums.CheckCodeTypeEnum;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.common.exception.BizException;
import com.usefullc.system.domain.DataConfig;
import com.usefullc.system.domain.DataDict;
import com.usefullc.system.entity.WebResult;
import com.usefullc.system.query.DataConfigQuery;
import com.usefullc.system.query.DataDictQuery;
import com.usefullc.system.service.CommonService;
import com.usefullc.system.service.DataConfigService;
import com.usefullc.system.service.DataDictService;
import com.usefullc.system.service.component.ImgCodeComponent;
import com.usefullc.system.service.file.FileResService;
import com.usefullc.system.vo.DataOptionVo;
import com.usefullc.system.vo.FileUploadResultVo;
import com.usefullc.system.vo.OptionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Sampson
 * @date: 2022-01-09 09:31
 */
@RestController
@RequestMapping(path = "/system/common/")
@Api(tags = "通用API")
public class CommonController extends BaseController {

    @Autowired
    private DataConfigService dataConfigService;

    @Autowired
    private ImgCodeComponent imgCodeComponent;

    @Qualifier("localFileUploadService")
    @Autowired
    private FileResService fileResService;

    @Autowired
    private DataDictService dataDictService;

    @Value("${usefullc.api.host}")
    private String apiHost;

    @Autowired
    private CommonService commonService;

    @ApiOperation(value = "获取系统所有枚举列表", response = WebResult.class)
    @GetMapping(path = "enumList", produces = "application/json")
    public Object enumList() {
//        WebResult webResult = WebResultBuilder.successResult();
//        webResult.put(getEnumKey(SmsCodeTypeEnum.class), SmsCodeTypeEnum.values());
//        webResult.put(getEnumKey(UserTypeEnum.class), UserTypeEnum.values());
//        webResult.put(getEnumKey(LoginTypeEnum.class), LoginTypeEnum.values());
//        webResult.put(getEnumKey(LocalEnum.class), LocalEnum.values());
//        webResult.put(getEnumKey(FormDataFromEnum.class), FormDataFromEnum.values());

        List<DataOptionVo> dataList = commonService.getEnumDataOptions();
        return WebResultBuilder.successResult(dataList);
    }





    @ApiOperation(value = "获取系统数据配置列表", response = WebResult.class)
    @GetMapping(path = "dataConfigList", produces = "application/json")
    public Object dataConfigList() {
        DataConfigQuery query = new DataConfigQuery();
        query.setEnable(YesNoEnum.YES.isBoole());
        List<DataConfig> dataList = dataConfigService.findAll(query);
        return WebResultBuilder.successResult(dataList);
    }


    @ApiOperation(value = "获取系统字典配置选择信息列表", response = WebResult.class)
    @GetMapping(path = "dataOptionList", produces = "application/json")
    public Object dataOptionList(DataDictQuery query) {
        List<DataOptionVo> dataList = new ArrayList<>();
        //系统字典
//        DataDictQuery query = new DataDictQuery();
        query.setParentId(0L);
        List<DataDict> dataDictList = dataDictService.findAll(query);
        for (DataDict dataDict : dataDictList) {
            DataOptionVo dataOptionVo = new DataOptionVo();
            dataOptionVo.setName(dataDict.getValue());
            dataList.add(dataOptionVo);
            DataDictQuery childQuery = new DataDictQuery();
            childQuery.setParentId(dataDict.getId());
            childQuery.setOrderByColumn("orderNo");
            childQuery.setAscOrDesc("asc");
            List<OptionVo> optionList = new ArrayList<>();
            dataOptionVo.setOptionList(optionList);
            List<DataDict> childDataDictList = dataDictService.findAll(childQuery);
            Integer type = dataDict.getType();
            DataDictTypeEnum dataDictTypeEnum = DataDictTypeEnum.getByCode(type);
            for (DataDict childDataDict : childDataDictList) {
                OptionVo optionVo = new OptionVo();
                optionVo.setText(childDataDict.getName());
                optionVo.setLabel(childDataDict.getName());
                optionVo.setTitle(childDataDict.getName());
                String value = childDataDict.getValue();
                Object optionValue = null;
                switch (dataDictTypeEnum) {
                    case BOOLEAN:
                        optionValue = BooleanUtils.toBoolean(value);
                        break;
                    case BYTE:
                        optionValue = value.getBytes();
                        break;
                    case INTEGER:
                        optionValue = NumberUtils.toInt(value);
                        break;
                    case DOUBLE:
                        optionValue = NumberUtils.toDouble(value);
                        break;
                    case STRING:
                        optionValue = value;
                        break;
                }
                optionVo.setValue(optionValue);
                optionList.add(optionVo);
            }
        }

        //系统枚举
        List<DataOptionVo> enumDataOptions = commonService.getEnumDataOptions();
        dataList.addAll(enumDataOptions);
        return WebResultBuilder.successResult(dataList);
    }


    @ApiOperation(value = "获取风控图形验证码", response = WebResult.class)
    @GetMapping(path = "getRiskImgCode", produces = "application/json")
    public Object getRiskImgCode(HttpServletRequest request) {
        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        String imgCode = imgCodeComponent.getImgCode(CheckCodeTypeEnum.RISK_RANDOM.getCode(),  deviceId);
        return WebResultBuilder.successResult(imgCode);
    }



    @ApiOperation(value = "文件上传", response = WebResult.class)
    @PostMapping(path = "upload", headers = "content-type=multipart/form-data", produces = "application/json")
    public WebResult upload(@RequestParam MultipartFile file, @RequestParam String biz) {
        try {
            byte[] bytes = file.getBytes();
            String oppositeFilePath = fileResService.upload(bytes, file.getOriginalFilename(), biz);
            FileUploadResultVo fileUploadResultVo = new FileUploadResultVo();
            oppositeFilePath = "/system/common/res" + oppositeFilePath;
            String absolutePath = apiHost + oppositeFilePath;
            fileUploadResultVo.setOppositePath(oppositeFilePath);
            fileUploadResultVo.setAbsolutePath(absolutePath);
            return WebResultBuilder.successResult(fileUploadResultVo);
        } catch (IOException e) {
            throw new BizException(e);
        }
    }

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "文件资源下载")
    @GetMapping(path = "res/**", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void res(HttpServletRequest request, HttpServletResponse response) {
        String requestURI = request.getRequestURI();
        try {
            String filePath = StringUtils.remove(requestURI, "/system/common/res");
            fileResService.download(filePath, response);
        } catch (Exception e) {
            throw new BizException(e);
        }
    }


}
